package com.caidan.search.service.impl;

import com.caidan.common.result.Result;
import com.caidan.framework.redis.key.MegProviderCacheKeyBuilder;
import com.caidan.framework.redis.key.UserProviderCacheKeyBuilder;
import com.caidan.search.service.MsgService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @项目名 CaiDanSearchSystem
 * @描述 实现类
 * @作者 小菜蛋
 * @时间 2024/12/2 16:56
 */

@Service
@Slf4j
public class MsgServiceImpl implements MsgService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MegProviderCacheKeyBuilder megProviderCacheKeyBuilder;

    @Override
    public Result<String> getCode(String phoneNumber) {
//        验证码生成
        String code = creatCode(5);
        if (null == code) {
            log.error("验证码生成出现问题");
        }
        System.out.println("验证码 : " + code);
//        储存Redis
        stringRedisTemplate.opsForValue().set(megProviderCacheKeyBuilder.buildUserInfoKey(phoneNumber),code);
        return Result.ok(code);
    }
    public static String creatCode(int n) {
        //3、定义一个字符串变量记录生成的随机字符
        String code = "";
        Random r = new Random();
        //2、定义一个for循环，循环n次，依次生成随机字符
        for (int i = 0; i < n; i++) {
            //i=0 1 2
            //3、生成一个随机字符，英文大、小写 数字（0 1 2 ）
            int type = r.nextInt(3);//0 1 2
            switch (type) {
                case 0:
                    //大写字符（A 65-Z 65+25）
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                case 1:
                    //小写字符（a 97-z 97+25）
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    //数字字符
                    code += r.nextInt(10);//0-9
                    break;
            }
        }
        return code;
    }
}
